<template>
    <div class="white-box">
        <el-form ref="ruleRef" :model="ruleForm" :rules="ruleCheck" label-width="120px">
            <el-form-item label="选择站点" prop="dc_id">
                <el-select v-model="ruleForm.dc_id" clearable placeholder="请选择站点">
                    <el-option :label="item.title" :value="item.dc_id" v-for="item in sitesArrs" :key="item.dc_id" />
                </el-select>
            </el-form-item>
            <el-form-item label="供应商名称" prop="names">
                <el-input v-model.trim="ruleForm.names" clearable placeholder="请输入供应商名称" />
            </el-form-item>
            <el-form-item label="供应商标签" prop="labels">
                <el-checkbox-group v-model="ruleForm.labels">
                    <el-checkbox :label="item.tag_id" v-for="item in labelArrs" :key="item.tag_id">
                        {{ item.title }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="手机号" prop="tel">
                <el-tooltip class="box-item" effect="dark" content="手机号可作为账号登录" placement="top-start">
                    <el-input v-model.trim="ruleForm.tel" maxlength="11" oninput="value=value.replace(/[^\d]/g,'')" placeholder="请输入供应商手机号" clearable>
                    </el-input>
                </el-tooltip>
            </el-form-item>
            <el-form-item label="登录密码" prop="pass">
                <el-input v-model.trim="ruleForm.pass" placeholder="请输入供应商登录密码" clearable show-password> </el-input>
            </el-form-item>
            <el-form-item label="供应商logo" prop="logo_paths" required>
                <div class="img-box flexs-center" @click.stop="clickSelectImg(1)" v-if="ruleForm.logo_paths == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div>
                <div class="img-selects" v-else>
                    <el-image class="img-selects__pic" :src="proxy.imgUrl + ruleForm.logo_paths + '!img_400'" :preview-src-list="logoList" fit="cover" />
                    <div class="img-del" @click.stop="delImg(1)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
                <p class="input-tips">限<code>1张</code>图片</p>
            </el-form-item>
            <el-form-item label="营业执照" prop="identity_paths">
                <div class="img-box flexs-center" @click.stop="clickSelectImg(2)" v-if="ruleForm.identity_paths == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div>
                <div class="img-selects" v-else>
                    <el-image
                        class="img-selects__pic"
                        :src="proxy.imgUrl + ruleForm.identity_paths + '!img_400'"
                        :preview-src-list="identityList"
                        fit="cover"
                    />
                    <div class="img-del" @click.stop="delImg(2)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
                <p class="input-tips">可选择<code>1张</code>图片</p>
                <!-- <div class="img-list" v-if="ruleForm.identity_paths.length > 0" style="flex: none">
                    <div class="img-selects" v-for="(item, index) in ruleForm.identity_paths" :key="index">
                        <el-image class="img-selects__pic" :src="proxy.imgUrl + item + '!img_400'" :preview-src-list="identityList" :initial-index="index" fit="cover" />
                        <div class="img-del" @click.stop="delImg(2, index)">
                            <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                        </div>
                    </div>
                </div>
                <div class="img-box flexs-center" @click.stop="clickIdentity" v-if="ruleForm.identity_paths.length < 1">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div> -->
            </el-form-item>
            <el-form-item label="身份证正面" prop="id_photo_front">
                <!-- <div class="img-box flexs-center" @click.stop="clickSelectImg(3)" v-if="ruleForm.id_photo_front == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div> -->
                <!-- <div class="img-selects" v-else>
                    <el-image
                        class="img-selects__pic"
                        :src="proxy.imgUrl + ruleForm.id_photo_front + '!img_400'"
                        :preview-src-list="photoFrontList"
                        fit="cover"
                    />
                    <div class="img-del" @click.stop="delImg(3)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div> -->
                <div class="card-img" @click.stop="clickSelectImg(3)" v-if="ruleForm.id_photo_front == ''">
                    <img :src="proxy.imgUrl + 'tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_2139e439a64db71da64948c64f6e3303.png'" />
                </div>
                <div class="card-select" v-else>
                    <el-image
                        class="card-select__pic"
                        :src="proxy.imgUrl + ruleForm.id_photo_front + '!img_400'"
                        :preview-src-list="photoFrontList"
                        fit="cover"
                    />
                    <div class="card-select-del" @click.stop="delImg(3)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
                <p class="input-tips">限<code>1张</code>图片</p>
            </el-form-item>
            <el-form-item label="身份证反面" prop="id_photo_back">
                <!-- <div class="img-box flexs-center" @click.stop="clickSelectImg(4)" v-if="ruleForm.id_photo_back == ''">
                    <el-icon color="#999" size="26px">
                        <UploadFilled />
                    </el-icon>
                </div>
                <div class="img-selects" v-else>
                    <el-image
                        class="img-selects__pic"
                        :src="proxy.imgUrl + ruleForm.id_photo_back + '!img_400'"
                        :preview-src-list="photoBackList"
                        fit="cover"
                    />
                    <div class="img-del" @click.stop="delImg(4)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div> -->
                <div class="card-img" @click.stop="clickSelectImg(4)" v-if="ruleForm.id_photo_back == ''">
                    <img :src="proxy.imgUrl + 'tenant_593be52a46f869eea8b31d146d21de7a/album/202304/20230413_0e06121c659c3db14866ac653764bd20.png'" />
                </div>
                <div class="card-select" v-else>
                    <el-image
                        class="card-select__pic"
                        :src="proxy.imgUrl + ruleForm.id_photo_back + '!img_400'"
                        :preview-src-list="photoBackList"
                        fit="cover"
                    />
                    <div class="card-select-del" @click.stop="delImg(4)">
                        <el-icon size="14px" color="#fff"><CloseBold /></el-icon>
                    </div>
                </div>
                <p class="input-tips">限<code>1张</code>图片</p>
            </el-form-item>
            <el-form-item label="是否有秒杀" prop="have_seckill" required>
                <el-switch
                    v-model="ruleForm.have_seckill"
                    inline-prompt
                    size="large"
                    active-text="是"
                    inactive-text="否"
                    :active-value="1"
                    :inactive-value="0"
                />
            </el-form-item>
            <el-form-item label="客服电话" prop="customer_tel" required>
                <el-input v-model.trim="ruleForm.customer_tel" oninput="value=value.replace(/[^\d-]/g,'')" placeholder="请输入客服电话" clearable> </el-input>
            </el-form-item>
            <el-form-item label="选择区域" prop="area_code" required>
                <div class="area-box">
                    <el-cascader ref="cascaderRef" v-model="ruleForm.area_code" :options="allArea" :props="props" placeholder="请选择省市区" />
                </div>
            </el-form-item>
            <el-form-item label="详细地址" prop="address">
                <el-input v-model.trim="ruleForm.address" placeholder="请输入详细地址" clearable> </el-input>
            </el-form-item>
            <el-form-item label="经纬度" prop="lat_lng">
                <el-input
                    v-model.trim="ruleForm.lat_lng"
                    readonly
                    :suffix-icon="ArrowRight"
                    placeholder="请选择当前位置的经纬度"
                    clearable
                    @click="clickLatAndLng"
                >
                </el-input>
            </el-form-item>
            <!-- <el-form-item label="提现百分比" prop="tixian_percent">
                <el-input
                    v-model.trim="ruleForm.tixian_percent"
                    oninput="value=value.replace(/[^\d.]/g,'')"
                    clearable
                    placeholder="请输入提现百分比"
                />
                <span class="input-icon">%</span>
                <p class="input-tips">填写0~100之间的数字(例如:填写96则表示提现100元实际得到100 x 96%=96元)</p>
            </el-form-item> -->
            <el-form-item label="佣金比例" prop="commiss_percent">
                <el-input v-model.trim="ruleForm.commiss_percent" oninput="value=value.replace(/[^\d.]/g,'')" clearable placeholder="请输入佣金比例" />
                <span class="input-icon">%</span>
                <p class="input-tips">填写0~100之间的数字</p>
            </el-form-item>
            <!-- <el-form-item label="到期时间" prop="end_time">
                <el-date-picker v-model="ruleForm.end_time" type="date" value-format="YYYY-MM-DD" placeholder="请选择到期时间" />
            </el-form-item> -->
            <el-form-item label="排序" prop="order_by">
                <el-input v-model.trim="ruleForm.order_by" oninput="value=value.replace(/[^\d]/g,'')" clearable placeholder="请输入排序数字" />
            </el-form-item>
            <el-form-item label="供应商简介" prop="reason">
                <el-input v-model.trim="ruleForm.reason" type="textarea" clearable :rows="6" show-word-limit maxlength="240" placeholder="请输入供应商简介" />
            </el-form-item>
            <el-form-item>
                <div class="foot-btn flexs-center" style="margin-top: 30px">
                    <el-button type="primary" :loading="form_loading" @click="submitForm(ruleRef)"> 确认添加 </el-button>
                    <el-button @click="resetForm(ruleRef)">重置</el-button>
                </div>
            </el-form-item>
        </el-form>

        <!-- 图片库 -->
        <picture-library :show="showImg" :select_multiple="false" @close="showImg = false" @select="selectImg"> </picture-library>

        <!-- 获取经纬度 -->
        <el-dialog v-model="dialogMap" title="获取经纬度" width="600px" :close-on-click-modal="false" :append-to-body="true" :destroy-on-close="true" draggable>
            <div class="p16">
                <div class="task-one">
                    <div class="task-one__item">
                        <span class="task-one__label">地址：</span>
                        <el-input placeholder="输入地址获取经纬度" v-model.trim="addrs" clearable style="width: 280px"></el-input>
                    </div>
                    <div class="task-one__btn">
                        <el-button type="primary" :loading="search_btn" :icon="Search" @click="handleSearch">获取</el-button>
                    </div>
                </div>
                <div id="container"></div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="confirmMap">确认地址</el-button>
                    <el-button @click="dialogMap = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <go-back />
</template>

<script setup>
import { getCurrentInstance, ref, onMounted, reactive, onBeforeUnmount } from "vue"
import { useRouter, useRoute } from "vue-router"
import { UploadFilled, CloseBold, ArrowRight, Search } from "@element-plus/icons-vue"
import PictureLibrary from "@components/PictureLibrary.vue"
import { jsonp } from "vue-jsonp"
import GoBack from "@components/GoBack.vue"

const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

onMounted(() => {
    getPublickSearch()
    getArea()
})

// 销毁
onBeforeUnmount(() => {
    map = null
    marker = null
    cascaderRef.value = null
    ruleRef.value = null
    // 移除绑定事件
    window.removeEvent = function () {
        qq.maps.event.removeListener(eventDragend)
        eventDragend = null
    }
})

/**
 * 腾讯地图-根据地址获取经纬度
 * @param {Boolean} dialogMap 地图弹窗
 * @param {String} locations 经纬度地址
 * @param {String} addrs 搜索字段
 * @param {Object} map Map 构造函数创建地图
 * @param {Function} initMap 初始化地图
 */
var map = null,
    marker = null,
    eventDragend = null
const addrs = ref("")
const locations = ref("")
const search_btn = ref(false)
const dialogMap = ref(false)
const handleSearch = () => {
    if (addrs.value == "") {
        proxy.$message({ message: "请输入详细地址！", type: "warning" })
        return
    }
    search_btn.value = true
    jsonp("https://apis.map.qq.com/ws/geocoder/v1/?address=", {
        output: "jsonp",
        address: addrs.value,
        key: "RIRBZ-LYM6O-Z73WF-S4A5Z-IEUB5-DXFYZ",
    })
        .then((res) => {
            search_btn.value = false
            if (res.status == 0) {
                locations.value = `${res.result.location.lat},${res.result.location.lng}`
                let center = new qq.maps.LatLng(res.result.location.lat, res.result.location.lng)
                map.panTo(center) // 重新设置地图中心点
                initMap(res.result.location.lat, res.result.location.lng)
            } else {
                proxy.$message({ message: res.message, type: "warning" })
            }
        })
        .catch((err) => {
            search_btn.value = false
        })
}
const clickLatAndLng = () => {
    dialogMap.value = true
    setTimeout(() => {
        initMap()
    }, 50)
}
const confirmMap = () => {
    dialogMap.value = false
    ruleForm.lat_lng = locations.value.split(",")
}
function initMap(lat = 39.90923, lng = 116.397428) {
    let myLatlng = new qq.maps.LatLng(lat, lng)
    let myOptions = {
        zoom: 17,
        center: myLatlng,
    }
    map = new qq.maps.Map(document.getElementById("container"), myOptions)
    marker = new qq.maps.Marker({
        // 设置标记
        position: myLatlng,
        draggable: true,
        animation: qq.maps.MarkerAnimation.DROP,
        map: map,
    })
    eventDragend = qq.maps.event.addListener(marker, "dragend", function (e) {
        // 监听标记拖动
        let latLng = marker.getPosition()
        map.setCenter(latLng)
        let lats = latLng.lat.toFixed(6)
        let lng = latLng.lng.toFixed(6)
        locations.value = `${lats},${lng}`
    })
}

/**
 * 添加
 * @param {Boolean} form_loading 弹窗按钮状态
 * @property {Array} ruleRef 表单规则
 * @property {Object} ruleForm  表单字段
 * @property {Object} ruleCheck  表单提示
 */
const form_loading = ref(false)
const ruleRef = ref(null)
const ruleForm = reactive({
    names: "",
    labels: [],
    tel: "",
    pass: "",
    customer_tel: "",
    reason: "",
    // tixian_percent: "",
    commiss_percent: "",
    // end_time: "",
    order_by: "100",
    area_code: [],
    address: "",
    lat_lng: [],
    logo_paths: "",
    identity_paths: "",
    id_photo_front: "",
    id_photo_back: "",
    dc_id: "",
    have_seckill: 0,
})
const ruleCheck = reactive({
    dc_id: [{ required: true, message: "请选择站点", trigger: "change" }],
    names: [{ required: true, message: "请输入供应商名称", trigger: "blur" }],
    labels: [{ type: "array", required: true, message: "请勾选供应商标签", trigger: "change" }],
    tel: [{ required: true, validator: proxy.$util.validPhone, trigger: "blur" }],
    pass: [{ required: true, message: "请输入供应商登录密码", trigger: "blur" }],
    customer_tel: [{ required: true, message: "请输入供应商客服电话", trigger: "blur" }],
    address: [{ required: true, message: "请输入详细地址", trigger: "blur" }],
    // lat_lng: [{ required: true, type: "array", message: "请选择当前位置的经纬度", trigger: "change" }],
    logo_paths: [{ required: true, message: "请选择供应商logo", trigger: "change" }],
    // id_photo_front: [{ required: true, message: "请选择身份证正面", trigger: "change" }],
    // id_photo_back: [{ required: true, message: "请选择身份证反面", trigger: "change" }],
    // identity_paths: [{ required: true, message: "请选择供应商营业执照", trigger: "change" }],
    area_code: [{ type: "array", required: true, message: "请选择省市区", trigger: "change" }],
    // tixian_percent: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    commiss_percent: [{ required: true, validator: proxy.$util.validNumOrPoint, trigger: "blur" }],
    // end_time: [{ required: true, message: "请选择到期时间", trigger: "change" }],
    order_by: [{ required: true, message: "请输入排序数字", trigger: "blur" }],
    // reason: [{ required: true, message: "请输入备注内容", trigger: "blur" }],
})
const submitForm = (formEl) => {
    // 确认
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            // areas[0].pathLabels 获取名称:['广东省','广州市','白云区']
            // areas[0].pathValues 获取code:['440000', '440100', '440111']
            let areas = cascaderRef.value.getCheckedNodes(false) // 获取级联选择的node
            form_loading.value = true
            let data = {
                dc_id: ruleForm.dc_id,
                title: ruleForm.names,
                tag_arr: ruleForm.labels,
                mobile: ruleForm.tel, // 手机号(账号)
                password: ruleForm.pass,
                phone: ruleForm.customer_tel, // 客服电话
                logo: ruleForm.logo_paths,
                id_photo_front: ruleForm.id_photo_front,
                id_photo_back: ruleForm.id_photo_back,
                account_photo: ruleForm.identity_paths,
                province_code: ruleForm.area_code[0],
                city_code: ruleForm.area_code[1],
                district_code: ruleForm.area_code[2],
                province: areas[0].pathLabels[0],
                city: areas[0].pathLabels[1],
                district: areas[0].pathLabels[2],
                house: ruleForm.address,
                // tixian_percent: ruleForm.tixian_percent,
                order_by: ruleForm.order_by,
                intro: ruleForm.reason,
                award_percent: ruleForm.commiss_percent,
                have_seckill: ruleForm.have_seckill,
            }
            if (ruleForm.lat_lng.length > 0) {
                data.lat = ruleForm.lat_lng[0]
                data.lng = ruleForm.lat_lng[1]
            }
            proxy.$axios
                .post("supplier/add", data)
                .then((res) => {
                    form_loading.value = false
                    if (res.data.code == 0) {
                        proxy.$message({ message: "添加供应商成功！", type: "success" })
                        router.push("/Supplier/SupplierList")
                    } else {
                        proxy.$message({ message: res.data.msg, type: "error" })
                    }
                })
                .catch((err) => {
                    form_loading.value = false
                })
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

/**
 * 添加logo、添加供应商资质
 * @property {Boolean} showImg 显示图片库
 * @property {Number} img_type 1是添加logo，2是添加营业执照，3是身份证正面，4是身份证反面
 * @property {Array} logoList logo预览数组
 * @property {Array} identityList 资质预览数组
 * @property {Array} photoFrontList 身份证正面预览
 * @property {Array} photoBackList 身份证反面预览
 * @property {Function} selectImg 选择图片
 */
const img_type = ref(1)
const showImg = ref(false)
const logoList = ref([])
const identityList = ref([])
const photoFrontList = ref([])
const photoBackList = ref([])
const selectImg = (val) => {
    showImg.value = false
    if (img_type.value == 1) {
        ruleForm.logo_paths = val[0].photo
        logoList.value.push(proxy.imgUrl + val[0].photo)
    } else if (img_type.value == 2) {
        ruleForm.identity_paths = val[0].photo
        identityList.value.push(proxy.imgUrl + val[0].photo)
    } else if (img_type.value == 3) {
        ruleForm.id_photo_front = val[0].photo
        photoFrontList.value.push(proxy.imgUrl + val[0].photo)
    } else {
        ruleForm.id_photo_back = val[0].photo
        photoBackList.value.push(proxy.imgUrl + val[0].photo)
    }
}
const delImg = (type, index) => {
    if (type == 1) {
        ruleForm.logo_paths = ""
        logoList.value = []
    } else if (type == 2) {
        ruleForm.identity_paths = ""
        identityList.value = []
        // ruleForm.identity_paths.splice(index, 1)
        // identityList.value.splice(index, 1)
    } else if (type == 3) {
        ruleForm.id_photo_front = ""
        photoFrontList.value = []
    } else {
        ruleForm.id_photo_back = ""
        photoBackList.value = []
    }
}
const clickSelectImg = (type) => {
    img_type.value = type
    showImg.value = true
}

// 获取标签
const labelArrs = ref([]) // 标签
const sitesArrs = ref([]) // 站点
function getPublickSearch() {
    proxy.$axios
        .get("supplier/add")
        .then((res) => {
            if (res.data.code == 0) {
                let result = res.data.data
                labelArrs.value = result.tag_list
                sitesArrs.value = result.dc_list
            } else {
                proxy.$message({ message: res.data.msg, type: "error" })
            }
        })
        .catch((err) => {})
}

/**
 * 选择省市区
 * @param {Array} allArea 存放省市区数组
 * @param {Object} cascaderRef 容器ref
 * @param {Function} getArea 请求json
 */
const allArea = ref([])
const cascaderRef = ref(null)
const props = {
    label: "name",
    value: "adcode",
    children: "districts",
}
function getArea() {
    proxy.$axios
        .get("gaode-area.json")
        .then((res) => {
            let result = res.data.districts
            allArea.value = result[0].districts
        })
        .catch((err) => {})
}
</script>
<script>
export default {
    name: "SupplierListAdd",
}
</script>

<style lang="less" scoped>
.card-select {
    position: relative;
    .card-select__pic {
        width: 245px;
        height: 144px;
        overflow: hidden;
    }
    .card-select-del {
        position: absolute;
        top: -6px;
        right: -6px;
        z-index: 11;
        width: 22px;
        height: 22px;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        overflow: hidden;
        background-color: #4b93fa;
        cursor: pointer;
    }
}
.input-icon {
    margin-left: @margin-sm;
    color: @gray-7;
}
.task-one {
    :deep(.el-input) {
        width: 340px;
    }
}

#container {
    width: 100%;
    height: 400px;
}

.el-form {
    :deep(.el-input) {
        width: 420px;
    }

    :deep(.el-textarea) {
        width: 420px;
    }
    :deep(.el-date-editor) {
        .el-input__wrapper {
            width: 420px;
        }
    }
}
</style>
